import React, {useEffect, useState} from "react";
import {Modal, Select, Upload} from "antd";
import LocalUtil from "@/utils/LocalUtil.ts";
import ObjApi from "@/api/ObjApi.ts";
import {ObjType} from "@/api/Types/ObjInterfaces.ts";

interface Props {
    open: boolean,
    setOpen: (open: boolean) => void
}

/**
 * 上传对象对话框
 * @param open 显示状态
 * @param setOpen 设置显示状态
 * @constructor
 */
const UploadObjModal: React.FC<Props> = ({open, setOpen}) => {
    const [objTypes, setObjTypes] = useState<Map<string, ObjType>>(null)
    const [targetType, setTargetType] = useState<string>(null)

    useEffect(() => {
        ObjApi.getObjTypes().then((data) => {
            const map = new Map<string, ObjType>()
            data.forEach(item => {
                map.set(item.id, item)
            })
            setObjTypes(map)
            setTargetType(data[0].id)
        })
    }, []);

    const ok = () => {
        setOpen(false)
    }

    const cancel = () => {
        setOpen(false)
    }

    if (objTypes == null) {
        return (
            <Modal
                open={open}
                onCancel={cancel}
                onOk={ok}
            >
            </Modal>
        )
    }

    return (
        <Modal
            open={open}
            onCancel={cancel}
            onOk={ok}
        >
            <Select
                onChange={(value) => {
                    setTargetType(value)
                }}
                options={(() => {
                    const res = []
                    objTypes.forEach((v, k) => {
                        res.push({
                            value: v.id,
                            label: v.contentName
                        })
                    })
                    return res
                })()}
                defaultValue={targetType}
                style={{minWidth: '100px'}}
            />

            <Upload.Dragger accept={objTypes.get(targetType).contentType}
                            action='api/obj'
                            headers={{
                                Authorization: LocalUtil.getToken(),
                                ContentType: objTypes.get(targetType).contentType,
                                type: objTypes.get(targetType).id
                            }}
                            multiple={true}
                            showUploadList={false}
                            onChange={ok}
            >
                <p>上传对象</p>
            </Upload.Dragger>
        </Modal>
    )
}

export default UploadObjModal